package core

import (
	"context"
	"fmt"

	"github.com/louloulin/dataflare/pkg/messages"
)

// SourceConnector 是源连接器接口
type SourceConnector interface {
	// Init 初始化连接器
	Init(ctx context.Context, config map[string]interface{}) error
	// Start 启动连接器
	Start(ctx context.Context) error
	// Stop 停止连接器
	Stop(ctx context.Context) error
	// Read 从源读取记录
	Read(ctx context.Context) (*messages.ReadDataResponse, error)
	// Commit 提交偏移
	Commit(ctx context.Context, offset interface{}) error
}

// SinkConnector 是接收器连接器接口
type SinkConnector interface {
	// Init 初始化连接器
	Init(ctx context.Context, config map[string]interface{}) error
	// Start 启动连接器
	Start(ctx context.Context) error
	// Stop 停止连接器
	Stop(ctx context.Context) error
	// Write 向接收器写入记录
	Write(ctx context.Context, record messages.Record) error
	// Flush 刷新缓冲记录
	Flush(ctx context.Context) error
}

// SourceConnectorFactory 是创建源连接器的工厂
type SourceConnectorFactory func() (SourceConnector, error)

// SinkConnectorFactory 是创建接收器连接器的工厂
type SinkConnectorFactory func() (SinkConnector, error)

// ConnectorRegistry 是连接器注册表
type ConnectorRegistry interface {
	// RegisterSourceConnector 注册源连接器
	RegisterSourceConnector(name string, factory SourceConnectorFactory)
	// RegisterSinkConnector 注册接收器连接器
	RegisterSinkConnector(name string, factory SinkConnectorFactory)
	// GetSourceConnector 获取源连接器
	GetSourceConnector(name string) (SourceConnector, error)
	// GetSinkConnector 获取接收器连接器
	GetSinkConnector(name string) (SinkConnector, error)
	// ListSourceConnectors 列出源连接器
	ListSourceConnectors() []string
	// ListSinkConnectors 列出接收器连接器
	ListSinkConnectors() []string
}

// ConnectorRegistryImpl 是ConnectorRegistry的实现
type ConnectorRegistryImpl struct {
	// sourceConnectors 是源连接器工厂
	sourceConnectors map[string]SourceConnectorFactory
	// sinkConnectors 是接收器连接器工厂
	sinkConnectors map[string]SinkConnectorFactory
}

// NewConnectorRegistry 创建一个新的连接器注册表
func NewConnectorRegistry() ConnectorRegistry {
	return &ConnectorRegistryImpl{
		sourceConnectors: make(map[string]SourceConnectorFactory),
		sinkConnectors:   make(map[string]SinkConnectorFactory),
	}
}

// RegisterSourceConnector 注册源连接器
func (r *ConnectorRegistryImpl) RegisterSourceConnector(name string, factory SourceConnectorFactory) {
	r.sourceConnectors[name] = factory
}

// RegisterSinkConnector 注册接收器连接器
func (r *ConnectorRegistryImpl) RegisterSinkConnector(name string, factory SinkConnectorFactory) {
	r.sinkConnectors[name] = factory
}

// GetSourceConnector 获取源连接器
func (r *ConnectorRegistryImpl) GetSourceConnector(name string) (SourceConnector, error) {
	factory, ok := r.sourceConnectors[name]
	if !ok {
		return nil, fmt.Errorf("source connector not found: %s", name)
	}
	return factory()
}

// GetSinkConnector 获取接收器连接器
func (r *ConnectorRegistryImpl) GetSinkConnector(name string) (SinkConnector, error) {
	factory, ok := r.sinkConnectors[name]
	if !ok {
		return nil, fmt.Errorf("sink connector not found: %s", name)
	}
	return factory()
}

// ListSourceConnectors 列出源连接器
func (r *ConnectorRegistryImpl) ListSourceConnectors() []string {
	connectors := make([]string, 0, len(r.sourceConnectors))
	for name := range r.sourceConnectors {
		connectors = append(connectors, name)
	}
	return connectors
}

// ListSinkConnectors 列出接收器连接器
func (r *ConnectorRegistryImpl) ListSinkConnectors() []string {
	connectors := make([]string, 0, len(r.sinkConnectors))
	for name := range r.sinkConnectors {
		connectors = append(connectors, name)
	}
	return connectors
}

// ConnectorManager 是连接器管理器
type ConnectorManager interface {
	// CreateSourceConnector 创建源连接器
	CreateSourceConnector(ctx context.Context, connectorType string, config map[string]interface{}) (string, error)
	// CreateSinkConnector 创建接收器连接器
	CreateSinkConnector(ctx context.Context, connectorType string, config map[string]interface{}) (string, error)
	// StartConnector 启动连接器
	StartConnector(ctx context.Context, connectorID string) error
	// StopConnector 停止连接器
	StopConnector(ctx context.Context, connectorID string) error
	// GetConnectorStatus 获取连接器状态
	GetConnectorStatus(ctx context.Context, connectorID string) (string, error)
	// ListConnectors 列出连接器
	ListConnectors(ctx context.Context) ([]string, error)
}

// ConnectorManagerImpl 是ConnectorManager的实现
type ConnectorManagerImpl struct {
	// registry 是连接器注册表
	registry ConnectorRegistry
	// system 是系统
	system System
}

// NewConnectorManager 创建一个新的连接器管理器
func NewConnectorManager(registry ConnectorRegistry, system System) ConnectorManager {
	return &ConnectorManagerImpl{
		registry: registry,
		system:   system,
	}
}

// CreateSourceConnector 创建源连接器
func (m *ConnectorManagerImpl) CreateSourceConnector(ctx context.Context, connectorType string, config map[string]interface{}) (string, error) {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送初始化连接器命令
	response, err := workflowSupervisor.Request(&messages.InitConnectorCommand{
		ConnectorType: connectorType,
		Config:        config,
	}, 30000)
	if err != nil {
		return "", err
	}

	// 解析响应
	initResponse, ok := response.(*messages.InitConnectorResponse)
	if !ok {
		return "", fmt.Errorf("unexpected response type: %T", response)
	}

	if !initResponse.Success {
		return "", fmt.Errorf("failed to create source connector: %s", initResponse.Error)
	}

	return initResponse.ConnectorID, nil
}

// CreateSinkConnector 创建接收器连接器
func (m *ConnectorManagerImpl) CreateSinkConnector(ctx context.Context, connectorType string, config map[string]interface{}) (string, error) {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送初始化连接器命令
	response, err := workflowSupervisor.Request(&messages.InitConnectorCommand{
		ConnectorType: connectorType,
		Config:        config,
	}, 30000)
	if err != nil {
		return "", err
	}

	// 解析响应
	initResponse, ok := response.(*messages.InitConnectorResponse)
	if !ok {
		return "", fmt.Errorf("unexpected response type: %T", response)
	}

	if !initResponse.Success {
		return "", fmt.Errorf("failed to create sink connector: %s", initResponse.Error)
	}

	return initResponse.ConnectorID, nil
}

// StartConnector 启动连接器
func (m *ConnectorManagerImpl) StartConnector(ctx context.Context, connectorID string) error {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送启动连接器命令
	response, err := workflowSupervisor.Request(&messages.StartConnectorCommand{
		ConnectorID: connectorID,
	}, 30000)
	if err != nil {
		return err
	}

	// 解析响应
	startResponse, ok := response.(*messages.StartConnectorResponse)
	if !ok {
		return fmt.Errorf("unexpected response type: %T", response)
	}

	if !startResponse.Success {
		return fmt.Errorf("failed to start connector: %s", startResponse.Error)
	}

	return nil
}

// StopConnector 停止连接器
func (m *ConnectorManagerImpl) StopConnector(ctx context.Context, connectorID string) error {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送停止连接器命令
	response, err := workflowSupervisor.Request(&messages.StopConnectorCommand{
		ConnectorID: connectorID,
	}, 30000)
	if err != nil {
		return err
	}

	// 解析响应
	stopResponse, ok := response.(*messages.StopConnectorResponse)
	if !ok {
		return fmt.Errorf("unexpected response type: %T", response)
	}

	if !stopResponse.Success {
		return fmt.Errorf("failed to stop connector: %s", stopResponse.Error)
	}

	return nil
}

// GetConnectorStatus 获取连接器状态
func (m *ConnectorManagerImpl) GetConnectorStatus(ctx context.Context, connectorID string) (string, error) {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送获取连接器状态命令
	response, err := workflowSupervisor.Request(&messages.GetConnectorStatusCommand{
		ConnectorID: connectorID,
	}, 30000)
	if err != nil {
		return "", err
	}

	// 解析响应
	statusResponse, ok := response.(*messages.GetConnectorStatusResponse)
	if !ok {
		return "", fmt.Errorf("unexpected response type: %T", response)
	}

	if !statusResponse.Success {
		return "", fmt.Errorf("failed to get connector status: %s", statusResponse.Error)
	}

	return statusResponse.Status, nil
}

// ListConnectors 列出连接器
func (m *ConnectorManagerImpl) ListConnectors(ctx context.Context) ([]string, error) {
	// 实现将在后续添加
	return nil, nil
}
